<template>
  <el-dialog
      v-model="dialogVisible"
      title="新建任务"
      width="500px"
      draggable
      @close="closeDialog"
      @keyup.enter = 'confirmDialog'
      v-loading="true"
  >
  <!-- 这里放入表单 -->
  <task-form-vue @update:form="updateFormData"></task-form-vue>
  <!-- 底部按钮 -->
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="cancelDialog">取消</el-button>
      <el-button type="primary" @click="confirmDialog">提交</el-button>
    </div>
  </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch} from "vue";
import TaskFormVue from "@/components/Form/TaskFormVue.vue";
import { ElMessage,ElLoading } from 'element-plus'
// const loadingInstance = ref(null)
const emits = defineEmits(["close","update:records"]);
const dialogVisible = ref(false);
const formData = ref({})
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
});
const data = ref({
  params:{},
  apiFile:'',
  apiFunction:''
})
const loading = ref(true)
const updateFormData = (newFormData) => {
  formData.value = newFormData
}
const cancelDialog = () => {
   closeDialog()
}
const modules = import.meta.glob('@/api/*.js') //一次性导入api文件夹中所有js文件

const confirmDialog = async () => {

  if (!formData.value.function || !formData.value.inputData) {
    ElMessage.error("请完整填写表单");
    return;
  }
  try {
    // 设置为加载状态
    // 以服务的方式调用
    const loadingInstance = ElLoading.service('.el-dialog')
    const {apiFile, apiFunction} = formData.value.function;
    // 下面的方法在构建生产环境时失效
    // const apiModule = await import(`/src/api/${apiFile}.js`)
    // console.log(modules)
    // modules里面的值是函数，所以要通过使用函数调用
    const apiModule = await modules[`/src/api/${apiFile}.js`]()
    // console.log(apiModule)
    // 请求的时候还要加入一些额外信息，如请求来源和请求功能
    data.value.params.inputData = formData.value.inputData.trim()
    // 这里使用params记录参数,后面也可以直接存入数据库中

    // data.value.params[inputData]
    data.value.apiFile = apiFile
    data.value.apiFunction = apiFunction
    console.log(data.value)
    const response = await apiModule[apiFunction](data.value)
    // 判断后端返回来的状态码
    if (response.status === 200) {
      // 触发父组件更新记录方法
      emits('update:records')
      console.log("提交的数据：", formData.value);
      // 关闭加载
      loadingInstance.close()
      ElMessage.success(response.data)
      closeDialog()
    } else {
      ElMessage.error(response.data)
    }
  }catch(error){

    // ElMessage.error("请求失败，请重试!")
    console.log(error)
    ElMessage.error(error)
  }finally {
    loading.value = false
  }
}

const closeDialog = () => {
  emits('close',false)
}
watch(() => props.isShow, (val) => {
  // console.log(val)
  dialogVisible.value = val

}, { immediate: true })
</script>

<style scoped>
/* 这里可以添加子组件的样式 */
</style>
